sudo docker network create mysql-replication

mkdir -p mysql-replication/{master,slave}/{data,conf}
cd mysql-replication

cat > master/conf/my.cnf << 'EOF'
[mysqld]
server-id = 1
log_bin = mysql-bin
binlog_format = ROW
expire_logs_days = 10
max_binlog_size = 100M
gtid_mode = ON
enforce_gtid_consistency = ON

# 通用配置
port = 3306
datadir = /var/lib/mysql
socket = /var/run/mysqld/mysqld.sock

# 字符集配置
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# 连接配置
max_connections = 1000
max_connect_errors = 1000

# 缓存配置
innodb_buffer_pool_size = 256M

# 跳过DNS解析
skip_name_resolve = ON
EOF

cat > slave/conf/my.cnf << 'EOF'
[mysqld]
server-id = 2
log_bin = mysql-bin
binlog_format = ROW
relay_log = mysql-relay-bin
read_only = ON
super_read_only = ON
gtid_mode = ON
enforce_gtid_consistency = ON

# 通用配置
port = 3306
datadir = /var/lib/mysql
socket = /var/run/mysqld/mysqld.sock

# 字符集配置
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

# 连接配置
max_connections = 1000
max_connect_errors = 1000

# 缓存配置
innodb_buffer_pool_size = 256M

# 跳过DNS解析
skip_name_resolve = ON
EOF

# 启动主服务器容器
sudo docker run -d \
  --name mysql-master \
  --network mysql-replication \
  -p 3306:3306 \
  -v $(pwd)/master/conf:/etc/mysql/conf.d \
  -e MYSQL_ROOT_PASSWORD=rootpassword123 \
  mysql:8.0.23 --read-only=0 --super-read-only=0

# 启动从服务器容器
sudo docker run -d \
  --name mysql-slave \
  --network mysql-replication \
  -p 3307:3306 \
  -v $(pwd)/slave/conf:/etc/mysql/conf.d \
  -e MYSQL_ROOT_PASSWORD=rootpassword123 \
  mysql:8.0.23 --read-only=0 --super-read-only=0

# 主服务器
CREATE USER 'replica_user'@'%' IDENTIFIED WITH mysql_native_password BY 'replica_password123';
GRANT REPLICATION SLAVE ON *.* TO 'replica_user'@'%';
FLUSH PRIVILEGES;

# 从服务器
STOP SLAVE;

CHANGE MASTER TO MASTER_HOST='mysql-master',MASTER_USER='replica_user',MASTER_PASSWORD='replica_password123',MASTER_AUTO_POSITION=882;

START SLAVE;

SHOW SLAVE STATUS\G